package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.dao.SaleListDao;
import com.atguigu.jxc.dao.SaleListGoodsDao;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.SaleListGoodsService;
import com.atguigu.jxc.util.AuthContextHolder;
import com.atguigu.jxc.util.DateUtil;
import com.atguigu.jxc.vo.PurchaseListAndReturnListVo;
import com.atguigu.jxc.vo.SaleListAndCustomerReturnList;
import com.atguigu.jxc.vo.SaleListVo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SaleListGoodsServiceImpl  implements SaleListGoodsService {

    @Autowired
    private SaleListGoodsDao saleListGoodsDao;

    @Autowired
    private SaleListDao saleListDao;

    @Autowired
    private GoodsDao goodsDao;

    //销售单保存
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SaleList saleList, String saleListGoodsStr, HttpSession session) {
        //获取用户信息
        User userInfo = AuthContextHolder.getUserInfo(session);
        //新增销售单
        saleList.setUserId(userInfo.getUserId());
        saleList.setTrueName(userInfo.getTrueName());
        saleListDao.saveSaleList(saleList);
        //将string转为对象
        List<SaleListGoods> saleListGoods = JSONObject.parseArray(saleListGoodsStr, SaleListGoods.class);
        saleListGoods.stream().forEach(item ->{
            //新增销售单明细
            item.setSaleListId(saleList.getSaleListId());
            saleListGoodsDao.saveSaleListGoods(item);
            //进货单添加对应添加商品库存
            Goods goods =goodsDao.getGoodsById(item.getGoodsId());
            //销售数量不能大于库存数量
            if (goods.getInventoryQuantity()>=item.getGoodsNum()){
                goods.setInventoryQuantity(goods.getInventoryQuantity()-item.getGoodsNum());
//                goods.setSellingPrice(item.getPrice());//修改销售价格
                goods.setState(2);//修改状态为销售出货
                goodsDao.updateGoods(goods);
            }else {
                throw new RuntimeException("销售数量不能大于库存数量");
            }
        });
    }

    //销售单查询（可查询条件：销售单号、客户、付款状态）
    @Override
    public Map<String, Object> list(String saleNumber, Integer customerId, Integer state, String sTime, String eTime) {
        //查询
        List<SaleList> saleListList=saleListDao.listSelect(saleNumber,customerId,state,sTime,eTime);
        Map<String, Object> map= new HashMap<>();
        map.put("rows",saleListList);
        return map;
    }

    //销售单商品信息 Integer saleListId
    @Override
    public Map<String, Object> goodsList(Integer saleListId) {
        //查询
        List<SaleListGoods> saleListGoodsList=saleListGoodsDao.goodsList(saleListId);
        Map<String, Object> map= new HashMap<>();
        map.put("rows",saleListGoodsList);
        return map;
    }

    //删除销售单 Integer saleListId
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer saleListId) {
        if (saleListId!=null){
            //删除销售单
            saleListDao.deleteSaleList(saleListId);
            //删除销售单明细
            saleListGoodsDao.deleteSaleListGoods(saleListId);
        }
    }

    //支付结算（修改销售单付款状态） Integer saleListId
    @Override
    public void updateState(Integer saleListId) {
        if (saleListId!=null){
            //根据id查询
            SaleList saleList =saleListDao.selectById(saleListId);
            //修改状态
            saleList.setState(1);//1 1已支付
            saleListDao.updateState(saleList);
        }
    }

    //销售统计（可根据 商品类别、商品编码或名称 条件查询）
    @Override
    public String count(String sTime, String eTime, Integer goodsTypeId, String codeOrName) {
        //  t_sale_list  t_sale_list_goods  t_customer   t_goods_type
        List<SaleListAndCustomerReturnList> SaleListVoList=saleListDao.count(sTime,eTime,goodsTypeId,codeOrName);
        Gson gson = new Gson();
        //把list转为json
        String json = gson.toJson(SaleListVoList);
        return json;
    }

    //按日统计接口
    @Override
    public String getSaleDataByDay(String sTime, String eTime) {
        try {
            //遍历期间日期
            List<String> timeSlotByDay = DateUtil.getTimeSlotByDay(sTime, eTime);
//            List<SaleListVo> saleDataByDays =new ArrayList<>();
            //方式一，如果统计返回null，直接属性赋值放入集合
//            for (String timeDay : timeSlotByDay) {
//                SaleListVo saleDataByDay = saleListDao.getSaleDataByDay(timeDay);
//                if (saleDataByDay==null){
//                    SaleListVo saleListVo = new SaleListVo();
//                    saleListVo.setDate(timeDay);
//                    saleListVo.setSaleTotal(0);
//                    saleListVo.setPurchasingTotal(0);
//                    saleListVo.setProfit(0);
//                    saleDataByDays.add(saleListVo);
//                }else {
//                    saleDataByDay.setDate(timeDay);
//                    saleDataByDays.add(saleDataByDay);
//                }
//            }

             //方式二：使用map做
            //方式三：sql进行处理返回值为0
            List<SaleListVo> saleDataByDays = timeSlotByDay.stream().map(timeDay -> {
                //查询一次保存
                SaleListVo saleDataByDay = saleListDao.getSaleDataByDay(timeDay);
                saleDataByDay.setDate(timeDay);
                return saleDataByDay;
            }).collect(Collectors.toList());
            Gson gson = new Gson();
            //把list转为json
            String json = gson.toJson(saleDataByDays);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return "查询日期异常";
        }
    }

    //按月统计接口
    @Override
    public String getSaleDataByMonth(String sTime, String eTime) {
        try {
            //遍历期间日期
            List<String> timeSlotByDay = DateUtil.getTimeSlotByMonth(sTime, eTime);
            //方式二：sql进行处理返回值为0
            List<SaleListVo> saleDataByDays = timeSlotByDay.stream().map(timeDay -> {
                //查询一次保存
                SaleListVo saleDataByDay = saleListDao.getSaleDataByMonth(timeDay);
                saleDataByDay.setDate(timeDay);
                return saleDataByDay;
            }).collect(Collectors.toList());
            Gson gson = new Gson();
            //把list转为json
            String json = gson.toJson(saleDataByDays);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return "查询月份异常";
        }
    }
}
